package models;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

/**
 * Created by yangxianming on 2018-12-18.
 * 从引用列表中替换目标字符串 ${}
 * ${}  $random{  $longtime
 */
public class DataReplace {
    private static String noSign;
    private static String haveSign;
    private static String frontStr;
    private static String beforeStr;

    public static String replace(HashMap<String, String> dictionary, String originalStr){
        //没有替换标记就提出
        if (!originalStr.contains("$") || !originalStr.contains("{") || !originalStr.contains("}"))
            return originalStr;

        try {
            while (true){
                String sign = "${";
                if (originalStr.contains(sign)){
                    decompose(originalStr, sign);
                    originalStr = frontStr + checkDollar(dictionary, noSign, haveSign) + beforeStr;
                    continue;
                }

                sign = "$random{";
                if (originalStr.contains(sign)){
                    decompose(originalStr, sign);
                    originalStr = frontStr + checkRandom(noSign, haveSign) + beforeStr;
                    continue;
                }

                sign = "$longtime{";
                if (originalStr.contains(sign)){
                    decompose(originalStr, sign);
                    originalStr = frontStr + checkLongTime(noSign, haveSign) + beforeStr;
                    continue;
                }

                break;
            }
        }catch (StringIndexOutOfBoundsException e){
            System.out.println("Exception:替换语法异常，见如下语句：" + originalStr);
        }

        return originalStr;
    }

    //将${}中的字符串
    private static String checkDollar(HashMap<String, String> dictionary, String targetStr, String targetStrSign){
        if (dictionary.containsKey(targetStr)){
            return dictionary.get(targetStr);
        }else {
            return targetStrSign.replace("{", "[").replace("}", "]");
        }
    }

    //$random{} 括号中支持3中参数
    //1. 0-9 中随机
    //2. a,b,c 3个值随机
    //3. 100 默认产生0-100随机值
    //如果不满足上面的参数将会返回空 ""
    private static String checkRandom(String targetStr, String targetStrSign){
        Random random = new Random();
        try {
            if (targetStr.contains("-")){
                String[] fromTo;
                fromTo = targetStr.split("-");
                int s = Integer.valueOf(fromTo[0].trim());
                int t = Integer.valueOf(fromTo[1].trim());
                return String.valueOf(s + random.nextInt(t-s) + 1);
            }
            else if (targetStr.contains(",")){
                String[] randomArray;
                randomArray = targetStr.split(",");
                for (String s:randomArray)
                    s = s.trim();
                return randomArray[random.nextInt(randomArray.length)];
            }else {
                return String.valueOf(random.nextInt(Integer.valueOf(targetStr)) + 1);
            }
        }catch (Exception e){
            return targetStrSign.replace("{", "[").replace("}", "]");
        }
    }

    //$longtime{}
    //1. 括号中为空,反回本地当前时间的13位时间戳
    //2. yyyy-MM-dd HH:mm:ss 返回具体时间的时间错
    //3. 如果格式异常或者时间异常将不会替换并返回原有值
    private static String checkLongTime(String targetStr, String targetStrSign){
        Date data = new Date();
        SimpleDateFormat formatter = null;
        //这个默认返回当前的13位时间戳
        if (targetStr.equals("")){
            Long longtime = data.getTime();
            return longtime.toString();
        }
        try {
            formatter = new SimpleDateFormat(targetStr);
            return formatter.format(new Date());
        }catch (Exception e){
            return targetStrSign.replace("{", "[").replace("}", "]");
        }
    }

    //分解字符串
    private static void decompose(String originalStr, String sign) throws StringIndexOutOfBoundsException{
        int lastDollarIndex = originalStr.lastIndexOf(sign);
        frontStr = originalStr.substring(0, lastDollarIndex);
        String t = originalStr.substring(lastDollarIndex, originalStr.length());
        haveSign = t.substring(0, t.indexOf("}")+1);
        noSign = haveSign.substring(sign.length(), haveSign.length()-1);
        beforeStr = t.substring(t.indexOf("}")+1, t.length());
    }


    //对其中的字符串做UrlEncode
//    private static NeedReplaceStringModel checkUrlEncode(ConfigDataModel acdm, String str) {
//        NeedReplaceStringModel nrsd = obgReplace(acdm, str);
//        try {
//            nrsd.string = URLEncoder.encode(nrsd.string, "UTF-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        nrsd.hasReplaced = true;
//        return nrsd;
//    }

    //对其中的字符串做UrlDecode
//    private static NeedReplaceStringModel checkUrlDecode(ConfigDataModel acdm, String str) {
//        NeedReplaceStringModel nrsd = obgReplace(acdm, str);
//        try {
//            nrsd.string = URLDecoder.decode(nrsd.string, "UTF-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        nrsd.hasReplaced = true;
//        return nrsd;
//    }

    //获取格式化日期  $getTime{}
//    private static NeedReplaceStringModel checkGetTime(ConfigDataModel acdm, String str){
//        NeedReplaceStringModel nrsd = obgReplace(acdm, str);
//        Date data = new Date();
//        SimpleDateFormat formatter;
//        String tempTime;
//        if (nrsd.string.equals("")){     //如果 $getTime{}中为空 返回默认格式字符串
//            formatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
//        }else {
//            formatter = new SimpleDateFormat(str);
//        }
//
//        tempTime = formatter.format(data);
//        nrsd.string = tempTime;
//        nrsd.hasReplaced = true;
//        return nrsd;
//    }

    //将日期做加减处理
    /*
        str  2015-04-04,year,+4,yyyy-MM-dd
        1. 输入的时间 格式暂时固定yyyy-MM-dd
        2. 偏移的时间段 暂时支持year month date
        3. 偏移量 -n or +n
        4. 输出格式
        */
    //供calendar.add第一个参数使用
//    private static NeedReplaceStringModel checkDateAdd(ConfigDataModel acdm, String str){
//        NeedReplaceStringModel nrsd = obgReplace(acdm, str);
//        HashMap<String, Integer> dateSign = new HashMap<String, Integer>();
//        dateSign.put("year", Calendar.YEAR);
//        dateSign.put("month", Calendar.MONTH);
//        dateSign.put("date", Calendar.DATE);
//
//        String[] strings = str.split(",");
//        for (int i = 0; i < strings.length; i++)
//            strings[i] = strings[i].trim(); //去空格
//
//        //格式化时间。如果有需要再加入hour minute second
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        String setDay = strings[0];     //第一个参数的原始日期
//        int deviation = Integer.valueOf(strings[2]);    //第三个参数的偏移量
//
//        Calendar calendar = Calendar.getInstance();
//        try {
//            calendar.setTime(sdf.parse(setDay));
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        calendar.add(dateSign.get(strings[1]), deviation);  //设置日期偏移量
//        //获取输出时间格式
//        String outDateFormat = "yyyy-MM-dd";
//        try {
//            outDateFormat = strings[3];
//        }catch (Exception e){
//            System.out.println("DateAdd fourth parameter null, outDateFormat get the default value: yyyy-MM-dd");
//        }
//        SimpleDateFormat sdf1 = new SimpleDateFormat(outDateFormat);
//        nrsd.string = sdf1.format(calendar.getTime());
//        nrsd.hasReplaced = true;
//        return nrsd;
//    }



}
